<template>
  <div class="control">
    <!-- 进度条 -->
    <div class="progress-container">
      <div class="time-display">
        <span class="current-time">{{ formatTime(currentTime) }}</span>
        <span class="total-time">{{ formatTime(duration) }}</span>
      </div>
      <div class="progress-bar" @click="seekTo">
        <div class="progress-bg"></div>
        <div class="progress-fill" :style="{ width: progressPercent + '%' }"></div>
        <div class="progress-thumb" :style="{ left: progressPercent + '%' }"></div>
      </div>
    </div>

    <!-- 控制按钮 -->
    <div class="controls">
      <div class="left">
        <div class="prev" v-cursor-pointer @click="prevMusic">
          <SvgIcon name="music-prev" />
        </div>
        <div class="play-pause" v-cursor-pointer @click="togglePlayPause">
          <el-icon v-if="isPlaying" :size="24"><VideoPause /></el-icon>
          <el-icon v-else :size="24"><VideoPlay /></el-icon>
        </div>
        <div class="next" v-cursor-pointer @click="nextMusic">
          <SvgIcon name="music-next" />
        </div>
      </div>
      <div class="right">
        <!-- 音量控制 -->
        <div class="volume-control" v-cursor-pointer @mouseenter="handleVolumeMouseEnter" @mouseleave="handleVolumeMouseLeave">
          <div class="volume-icon" @click="toggleMute">
            <el-icon v-if="isMuted || volume === 0" :size="20"><Mute /></el-icon>
            <el-icon v-else-if="volume < 0.5" :size="20"><Microphone /></el-icon>
            <el-icon v-else :size="20"><Headset /></el-icon>
          </div>
          <!-- 音量滑块 -->
          <div class="volume-slider-container" v-show="showVolumeSlider" @mouseenter="handleSliderMouseEnter" @mouseleave="handleSliderMouseLeave">
            <div class="volume-slider" @click="adjustVolume">
              <div class="volume-bg"></div>
              <div class="volume-fill" :style="{ height: volumePercent + '%' }"></div>
              <div class="volume-thumb" :style="{ bottom: volumePercent + '%' }"></div>
            </div>
            <div class="volume-text">{{ Math.round(volume * 100) }}%</div>
          </div>
        </div>
        <div class="mode" v-cursor-pointer>
          <el-tooltip content="播放模式" placement="top">
            <div class="icon">
              <el-popover placement="top" :width="200" trigger="click">
                <template #reference>
                  <SvgIcon :name="musicStore.playMode.icon" />
                </template>
                <ul class="icons">
                  <li v-for="(item, index) in musicStore.modes" :key="item.icon" @click="changeMode(item,index)" :class="{active: item.value === musicStore.playMode.value}">
                    <SvgIcon style="color: #000" :name="item.icon" />
                    <span>{{ item.name }}</span>
                  </li>
                </ul>
              </el-popover>
            </div>
          </el-tooltip>
        </div>
        <div class="list" v-cursor-pointer>
          <el-tooltip content="播放列表" placement="top">
            <div class="icon">
              <el-popover placement="top-start" :width="300" trigger="click">
                <template #reference>
                  <SvgIcon name="music-list" />
                </template>
                <ul class="music-list" v-if="musicStore.musicList.length > 0">
                  <li
                    v-for="(item, index) in musicStore.musicList"
                    :key="item.id"
                    @click="changeMusic(item)"
                    :class="{ active: item.id === musicStore.currentMusic.id }"
                  >
                    <div class="index">{{ index + 1 }}</div>
                    <div class="name">{{ item.title }}</div>
                    <div class="artist">{{ item.artist }}</div>
                    <el-icon class="ml-5" color="#FF0000" @click.stop="deleteMusic(item)"><DeleteFilled /></el-icon>
                  </li>
                </ul>
                <div v-else>暂无歌曲</div>
              </el-popover>
            </div>
          </el-tooltip>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onUnmounted } from "vue"
import { useMusicStore } from "@/store/modules/music"

const musicStore = useMusicStore()

// 播放状态
const isPlaying = ref(false)
// 当前播放时间
const currentTime = ref(0)
// 总时长
const duration = ref(0)
// 音量控制
const volume = ref(1)
const isMuted = ref(false)
const previousVolume = ref(1)
const showVolumeSlider = ref(false)
const volumeTimeout = ref<number | null>(null)

// 计算进度百分比
const progressPercent = computed(() => {
  if (duration.value === 0) return 0
  return (currentTime.value / duration.value) * 100
})

// 计算音量百分比
const volumePercent = computed(() => {
  return volume.value * 100
})

// 格式化时间
const formatTime = (time: number) => {
  const minutes = Math.floor(time / 60)
  const seconds = Math.floor(time % 60)
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 监听播放器状态
watch(() => musicStore.player, (player: any) => {
  if (player) {
    // 监听播放状态
    const updatePlayState = () => {
      isPlaying.value = !player.paused
    }

    // 监听时间更新
    const updateTime = () => {
      currentTime.value = player.currentTime || 0
      duration.value = player.duration || 0
    }

    // 添加事件监听器
    player.addEventListener('play', updatePlayState)
    player.addEventListener('pause', updatePlayState)
    player.addEventListener('timeupdate', updateTime)
    player.addEventListener('loadedmetadata', updateTime)

    // 初始化状态
    updatePlayState()
    updateTime()

    // 设置初始音量
    if (player.volume !== undefined) {
      volume.value = player.volume
    }
  }
}, { immediate: true })

// 播放/暂停切换
const togglePlayPause = () => {
  if (!musicStore.player) return

  if (isPlaying.value) {
    musicStore.player.pause()
  } else {
    musicStore.player.play()
  }
}

// 跳转到指定时间
const seekTo = (event: MouseEvent) => {
  if (!musicStore.player || !duration.value) return

  const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
  const clickX = event.clientX - rect.left
  const width = rect.width
  const seekTime = (clickX / width) * duration.value

  musicStore.player.currentTime = seekTime
}

// 音量控制
const adjustVolume = (event: MouseEvent) => {
  if (!musicStore.player) return

  const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
  const clickY = event.clientY - rect.top
  const height = rect.height
  const newVolume = Math.max(0, Math.min(1, 1 - (clickY / height)))

  volume.value = newVolume
  musicStore.player.volume = newVolume

  // 更新静音状态
  if (newVolume === 0) {
    isMuted.value = true
  } else {
    isMuted.value = false
  }
}

// 切换静音
const toggleMute = () => {
  if (!musicStore.player) return

  if (isMuted.value) {
    // 取消静音
    volume.value = previousVolume.value
    musicStore.player.volume = previousVolume.value
    isMuted.value = false
  } else {
    // 静音
    previousVolume.value = volume.value
    volume.value = 0
    musicStore.player.volume = 0
    isMuted.value = true
  }
}

// 列表切换歌曲
const changeMusic = (item: any) => {
  musicStore.setCurrentMusic(item)
}

// 删除歌曲
const deleteMusic = (item: any) => {
  musicStore.deleteMusic(item)
}

// 切换播放模式
const changeMode = (val: any, index: number) => {
  musicStore.changeMode(index)
}

// 播放下一首
const nextMusic = () => {
  musicStore.nextMusic()
}

// 播放上一首
const prevMusic = () => {
  musicStore.prevMusic()
}

// 处理音量控制鼠标进入
const handleVolumeMouseEnter = () => {
  if (volumeTimeout.value) {
    clearTimeout(volumeTimeout.value)
    volumeTimeout.value = null
  }
  showVolumeSlider.value = true
}

// 处理音量控制鼠标离开
const handleVolumeMouseLeave = () => {
  volumeTimeout.value = setTimeout(() => {
    showVolumeSlider.value = false
  }, 300) as any
}

// 处理音量滑块容器鼠标进入
const handleSliderMouseEnter = () => {
  if (volumeTimeout.value) {
    clearTimeout(volumeTimeout.value)
    volumeTimeout.value = null
  }
  showVolumeSlider.value = true
}

// 处理音量滑块容器鼠标离开
const handleSliderMouseLeave = () => {
  volumeTimeout.value = setTimeout(() => {
    showVolumeSlider.value = false
  }, 300) as any
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (volumeTimeout.value) {
    clearTimeout(volumeTimeout.value)
    volumeTimeout.value = null
  }
})
</script>

<style scoped lang="scss">
.control {
  width: 1280px;
  height: 120px;
  border: 2px solid #fff;
  border-radius: 10px;
  margin: 0 auto;
  margin-top: 100px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);

  .progress-container {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;

    .time-display {
      display: flex;
      justify-content: space-between;
      width: 100%;
      color: #fff;
      font-size: 12px;

      .current-time, .total-time {
        font-weight: 500;
      }
    }

    .progress-bar {
      width: 100%;
      height: 6px;
      background: rgba(255, 255, 255, 0.3);
      border-radius: 3px;
      position: relative;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        height: 8px;
        .progress-thumb {
          transform: translate(-50%, -50%) scale(1.2);
        }
      }

      .progress-bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 3px;
      }

      .progress-fill {
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        background: linear-gradient(90deg, #409eff, #67c23a);
        border-radius: 3px;
        transition: width 0.1s ease;
      }

      .progress-thumb {
        position: absolute;
        top: 50%;
        width: 12px;
        height: 12px;
        background: #fff;
        border-radius: 50%;
        transform: translate(-50%, -50%);
        transition: all 0.3s;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
      }
    }
  }

  .controls {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 5px;
    .left {
      display: flex;
      align-items: center;
      gap: 20px;

      .prev, .next {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.2);
        transition: all 0.3s;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
          transform: scale(1.1);
        }

        svg {
          width: 24px;
          height: 24px;
          color: #fff;
        }
      }

      .play-pause {
        width: 60px;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: linear-gradient(135deg, #409eff, #67c23a);
        transition: all 0.3s;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);

        &:hover {
          transform: scale(1.1);
          box-shadow: 0 6px 16px rgba(64, 158, 255, 0.6);
        }

        .el-icon {
          color: #fff;
        }
      }
    }

    .right {
      display: flex;
      align-items: center;
      gap: 20px;

      .volume-control {
        position: relative;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.2);
        transition: all 0.3s;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
          transform: scale(1.1);
        }

        .volume-icon {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
        }

        .volume-slider-container {
          position: absolute;
          bottom: 50px;
          left: 50%;
          transform: translateX(-50%);
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 10px;
          padding: 15px;
          background: rgba(0, 0, 0, 0.8);
          border-radius: 10px;
          backdrop-filter: blur(10px);
          z-index: 1000;

          .volume-slider {
            width: 20px;
            height: 100px;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 10px;
            position: relative;
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
              background: rgba(255, 255, 255, 0.4);
            }

            .volume-bg {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              border-radius: 10px;
            }

            .volume-fill {
              position: absolute;
              bottom: 0;
              left: 0;
              width: 100%;
              background: linear-gradient(to top, #409eff, #67c23a);
              border-radius: 10px;
              transition: height 0.1s ease;
            }

            .volume-thumb {
              position: absolute;
              left: 50%;
              width: 16px;
              height: 16px;
              background: #fff;
              border-radius: 50%;
              transform: translate(-50%, 50%);
              transition: all 0.3s;
              box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            }
          }

          .volume-text {
            color: #fff;
            font-size: 12px;
            font-weight: 500;
          }
        }
      }

      .mode, .list {
        position: relative;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.2);
        transition: all 0.3s;
        cursor: pointer;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
          transform: scale(1.1);
          box-shadow: 0 4px 12px rgba(255, 255, 255, 0.2);
        }

        .icon {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          transition: all 0.3s;

          svg {
            width: 24px;
            height: 24px;
            color: #fff;
            transition: all 0.3s;
          }
        }

        &:active {
          transform: scale(0.95);
        }
      }

      .mode {
        &:hover {
          background: linear-gradient(135deg, rgba(64, 158, 255, 0.3), rgba(103, 194, 58, 0.3));

          .icon svg {
            color: #409eff;
            transform: rotate(15deg);
          }
        }
      }

      .list {
        &:hover {
          background: linear-gradient(135deg, rgba(255, 193, 7, 0.3), rgba(255, 87, 34, 0.3));

          .icon svg {
            color: #ffc107;
            transform: scale(1.1);
          }
        }
      }
    }
  }
}

::v-deep(.el-popper) {
  background-color: transparent !important;
  color: #409eff !important;
}

.el-popover {
  padding: 0;
  margin: 0;
  outline: none;

  ul.icons {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    list-style: none;
    padding: 0;
    li {
      width: 100%;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      justify-content: center;
      padding: 12px;
      border-radius: 10px;
      transition: all 0.3s;
      cursor: pointer;
      background: rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(10px);

      &:hover {
        background: linear-gradient(135deg, #409eff, #67c23a);
        color: #fff;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }

      &:last-child {
        margin-bottom: 0;
      }

      &.active {
        background: linear-gradient(135deg, #409eff, #67c23a);
        border: 2px solid #409eff;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
        transform: translateY(-2px);

        svg {
          color: #fff !important;
          border-color: #fff;
          background-color: rgba(255, 255, 255, 0.2);
        }

        span {
          color: #fff;
        }
      }

      svg {
        width: 24px;
        height: 24px;
        color: #409eff;
        border: 2px solid #409eff;
        background-color: rgba(64, 158, 255, 0.1);
        padding: 8px;
        border-radius: 50%;
        transition: all 0.3s;
      }

      span {
        margin-left: 12px;
        font-weight: 500;
        font-size: 14px;
        color: #333;
        transition: all 0.3s;
      }
    }
  }
  ul.music-list {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    list-style: none;
    padding: 0;
    max-height: 300px;
    overflow-y: auto;

    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-track {
      background: rgba(255, 255, 255, 0.1);
      border-radius: 2px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(255, 255, 255, 0.3);
      border-radius: 2px;
    }

    li {
      width: 100%;
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      justify-content: space-between;
      padding: 12px;
      border-radius: 10px;
      transition: all 0.3s;
      cursor: pointer;
      background: rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(10px);

      &:hover,:active {
        background: linear-gradient(135deg, rgba(255, 193, 7, 0.2), rgba(255, 87, 34, 0.2));
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(255, 193, 7, 0.3);
      }

      &.active {
        background: linear-gradient(135deg, #409eff, #67c23a);
        border: 2px solid #409eff;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

        .name, .artist {
          color: #fff;
        }

        .index {
          background: #fff;
          color: #409eff;
        }
      }

      .name {
        flex: 1;
        font-size: 14px;
        font-weight: 500;
        margin-left: 12px;
        max-width: 120px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        color: #333;
      }

      .index {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        background: linear-gradient(135deg, #409eff, #67c23a);
        font-size: 12px;
        font-weight: bold;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
      }

      .artist {
        font-size: 12px;
        color: #666;
        max-width: 80px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin-right: 8px;
      }

      .el-icon {
        transition: all 0.3s;

        &:hover {
          transform: scale(1.2);
          color: #f56c6c;
        }
      }
    }
  }
}
</style>
